package service

import (
	"context"
	coreV1 "k8s.io/api/core/v1"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
)

func CreateConfigMap(clientSet *kubernetes.Clientset, request CreateConfigmapRequest) (configMapInfo *coreV1.ConfigMap, err error) {
	configMap := &coreV1.ConfigMap{
		ObjectMeta: metaV1.ObjectMeta{
			Name: request.FileName,
		},
		Data: request.Data,
	}

	configMapInfo, err = clientSet.CoreV1().ConfigMaps(request.NamespaceName).Create(context.TODO(), configMap, metaV1.CreateOptions{})
	if err != nil {
		return configMapInfo, err
	}
	return configMapInfo, nil
}

func GetConfigMapList(clientSet *kubernetes.Clientset, namespaceName string) (configMapList *coreV1.ConfigMapList, err error) {
	configMapList, err = clientSet.CoreV1().ConfigMaps(namespaceName).List(context.TODO(), metaV1.ListOptions{})
	if err != nil {
		return nil, err
	}
	return configMapList, err
}

func GetConfigMap(clientSet *kubernetes.Clientset, namespaceName, configmapName string) (configmapInfo *coreV1.ConfigMap, err error) {
	configmapInfo, err = clientSet.CoreV1().ConfigMaps(namespaceName).Get(context.TODO(), configmapName, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return configmapInfo, err
}

func ApplyConfigMap(clientSet *kubernetes.Clientset, request ApplyConfigMapRequest) (configmapInfo *coreV1.ConfigMap, err error) {

	configmapInfo, err = clientSet.CoreV1().ConfigMaps(request.NamespaceName).Get(context.TODO(), request.ConfigmapName, metaV1.GetOptions{})
	if err != nil {
		return nil, err
	}

	configmapInfo.Data = request.Data

	configmapInfo, err = clientSet.CoreV1().ConfigMaps(request.NamespaceName).Update(context.TODO(), configmapInfo, metaV1.UpdateOptions{})
	if err != nil {
		return configmapInfo, err
	}

	return configmapInfo, nil
}

func DeleteConfigMap(clientSet *kubernetes.Clientset, request DeleteConfigmapRequest) (err error) {
	err = clientSet.CoreV1().ConfigMaps(request.NamespaceName).Delete(context.TODO(), request.ConfigmapName, metaV1.DeleteOptions{})
	if err != nil {
		return err
	}
	return nil
}
